package com.bawei.module_goods.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_goods.R
import com.bawei.module_goods.entity.Sku
import com.google.android.material.bottomsheet.BottomSheetDialogFragment

class SkuListBottomSheetDialog(
    private val skuList: List<Sku>,
    private val onConfirm: ((Sku?) -> Unit)? = null
) : BottomSheetDialogFragment() {

    private var selectedSku: Sku? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val view = inflater.inflate(R.layout.dialog_sku_list_bottom_sheet, container, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.rvSkuList)
        val btnConfirm = view.findViewById<TextView>(R.id.btnConfirm)
        val btnCancel = view.findViewById<TextView>(R.id.btnCancel)

        recyclerView.layoutManager = LinearLayoutManager(context)
        // 默认选中第一个SKU
        selectedSku = skuList.firstOrNull()
        val adapter = SkuSimpleAdapter(skuList, skuList.indexOf(selectedSku)) { sku, pos ->
            selectedSku = sku
        }
        recyclerView.adapter = adapter

        btnConfirm.setOnClickListener {
            onConfirm?.invoke(selectedSku)
            dismiss()
        }
        btnCancel.setOnClickListener {
            dismiss()
        }
        return view
    }

    override fun onStart() {
        super.onStart()
        dialog?.setCanceledOnTouchOutside(false)
        isCancelable = false
    }
}

class SkuSimpleAdapter(
    private val list: List<Sku>,
    private var selectedPos: Int = 0,
    private val onSelect: (Sku, Int) -> Unit
) : RecyclerView.Adapter<SkuSimpleAdapter.VH>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VH {
        val tv = LayoutInflater.from(parent.context).inflate(R.layout.item_sku_simple, parent, false) as TextView
        return VH(tv)
    }
    override fun getItemCount() = list.size
    override fun onBindViewHolder(holder: VH, position: Int) {
        val sku = list[position]
        holder.tv.text = sku.skuName ?: ""
        holder.tv.isSelected = position == selectedPos
        // 设置item之间的竖直间距
        val params = holder.tv.layoutParams as? ViewGroup.MarginLayoutParams
        params?.topMargin = if (position == 0) 0 else 12
        holder.tv.layoutParams = params
        holder.tv.setOnClickListener {
            val old = selectedPos
            selectedPos = position
            notifyItemChanged(old)
            notifyItemChanged(position)
            onSelect(sku, position)
        }
    }
    class VH(val tv: TextView) : RecyclerView.ViewHolder(tv)
} 